package gwt.immunology.server.service;

import gwt.immunology.client.service.RoleService;
import gwt.immunology.server.converter.RoleDtoConverter;
import gwt.immunology.shared.GenericDto;
import gwt.immunology.shared.ResultSetDto;

import java.util.List;

import models.Role;
import play.Logger;
import play.modules.gwt2.GWT2Service;
import play.modules.gwt2.GWT2ServicePath;

@GWT2ServicePath("/immunology/role")
public class RoleServiceImpl extends GWT2Service implements RoleService {

    @Override
    public GenericDto registerNewRole(GenericDto roleDto) {
	GenericDto result = null;
	if (roleDto != null && !roleDto.isEmpty()) {
	    Role role = RoleDtoConverter.convertGenericDtoToRole(roleDto);
	    Logger.info("registering new role");
	    role = Role.em().merge(role);
	    result = RoleDtoConverter.convertRoleToGenericDto(role);
	} else {
	    Logger.warn("can't register role with null value");
	}
	return result;
    }

    @Override
    public void deleteRoleById(Long roleId) {
	if (roleId != null) {
	    Role role = Role.em().find(Role.class, roleId);
	    if (role != null) {
		Logger.info("deleting role by id = " + roleId);
		Role.em().remove(role);
	    } else {
		Logger.warn("can't delete role with null value");
	    }
	} else {
	    Logger.warn("can't delete role by id = " + roleId);
	}
    }

    @Override
    public GenericDto getRoleById(Long roleId) {
	GenericDto result = null;
	if (roleId != null) {
	    Logger.info("retrieving role by id = " + roleId);
	    Role role = Role.em().find(Role.class, roleId);
	    result = RoleDtoConverter.convertRoleToGenericDto(role);
	} else {
	    Logger.warn("can't retrieve role by id = " + roleId);
	}
	return result;
    }

    @Override
    public GenericDto editRole(GenericDto roleDto) {
	GenericDto result = null;
	if (roleDto != null && !roleDto.isEmpty()) {
	    Role role = RoleDtoConverter.convertGenericDtoToRole(roleDto);
	    Logger.info("editing role with id = " + role.roleId);
	    role = Role.em().merge(role);
	    result = RoleDtoConverter.convertRoleToGenericDto(role);
	} else {
	    Logger.warn("can't edit role with null value");
	}
	return result;
    }

    @Override
    public ResultSetDto getAllRoles() {
	ResultSetDto result = null;
	Logger.info("retrieving all roles");
	List<Role> roles = Role.all().fetch();
	result = RoleDtoConverter.convertRolesToResultSetDto(roles);
	return result;
    }

}
